import {
  Controller,
  Get,
  Post,
  Body,
  UseGuards,
  Param,
  Put,
  Delete,
} from '@nestjs/common';
import { RecordService } from './record.service';
import { CreateRecordDto } from './dto/create-record.dto';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { Roles } from '../../common/decorator/roles.decorator';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Role } from '../../common/types/role';
import CurrentUser from '../../common/decorator/current-user.decorator';
import { UserEntity } from '../user/entities/user.entity';
import { QueryPageDto } from '../../common/dto/query.page.dto';
import { Prisma } from '@prisma/client';
import { QueryRecordDto } from './dto/query-record.dto';
import { getDayRange } from '../../common/utils/util';
import { UpdateRecordDto } from './dto/update-record.dto';

@Controller('record')
@ApiTags('生产管理')
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
export class RecordController {
  constructor(private readonly recordService: RecordService) {}

  @Post()
  @Roles(Role.FINANCE)
  @UseGuards(RolesGuard)
  create(
    @Body() createRecordDto: CreateRecordDto,
    @CurrentUser() user: UserEntity,
  ) {
    return this.recordService.create(createRecordDto, user.id);
  }

  @Post('page')
  async findByPage(@Body() query: QueryPageDto<QueryRecordDto>) {
    const dayRange = getDayRange(query.model.date);

    const where: Prisma.recordWhereInput = {
      date: {
        lt: dayRange[1],
        gte: dayRange[0],
      },
      worker: {
        name: {
          contains: query.model.worker || undefined,
        },
      },
      style: {
        groupId: query.model.group || undefined,
      },
    };

    const list = await this.recordService.queryPage(query, where, {
      include: {
        worker: {
          select: {
            id: true,
            name: true,
          },
        },
        style: {
          include: {
            process: true,
            group: {
              select: {
                id: true,
                name: true,
              },
            },
            model: {
              select: {
                code: true,
                id: true,
                name: true,
              },
            },
          },
        },
        size: true,
      },
    });
    list.record.map((item: any) => {
      item.process = item.style.process.find(
        (p: any) => p.index == item.processIndex,
      );
      delete item.style.process;
    });

    return list;
  }

  @Get(':id')
  getOne(@Param('id') id: string) {
    return this.recordService.findOne(id);
  }

  @Put(':id')
  @Roles(Role.FINANCE)
  @UseGuards(RolesGuard)
  update(@Param('id') id: string, @Body() updateForm: UpdateRecordDto) {
    return this.recordService.update(id, updateForm);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.recordService.remove(id);
  }
}
